package org.example.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.domain.Identity;
import org.example.domain.Menu;
import org.example.mapper.MenuMapper;
import org.example.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author blackTry
 * @since 2021-04-27
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Menu> getMenusByIdentityId() {
        Long identityId = ((Identity) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 从redis中获取数据
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + identityId);
        // 没有就从数据库中查
        if (CollectionUtil.isEmpty(menus)) {
            menus = this.baseMapper.getMenusByIdentityId(identityId);
            // 将数据设置到缓存中
            valueOperations.set("menu_" + identityId, menus);
        }
        return menus;
    }

    @Override
    public List<Menu> getMenusByRole() {
        return this.baseMapper.getMenusByRole();
    }
}
